<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/13
 * Time: 11:45
 */
namespace App\Models\Api;
use Illuminate\Database\Eloquent\Model;
use App\Models\Api\Base;
use App\Models\Api\Goods;

use Cache;

class Rectification extends Base
{
    protected $table = 'rectification';
    protected $dateFormat ='U';
    public $guarded = [];
    const  CREATED_AT  = 'create_time';
    const  UPDATED_AT  = 'update_time';
    public $timestamps = true;

    public function setCreateTimeAttr($value)
    {
        return time();
    }

    public function setUpdateTimeAttr($value)
    {
        return time();
    }

    /**
     * 关联生时校正  事件模型
     * @return \think\model\relation\HasMany
     */
    public function events()
    {
         return $this->hasMany('App\Models\Api\RectificationEvent','reid','id');
    }

    /**
     * 关联生时校正 结果模型
     * @return \think\model\relation\HasMany
     */
    public function result()
    {
        return $this->hasMany('App\Models\Api\RectificationResult','reid','id');
    }

    public function orders()
    {
        return $this->hasOne('App\Models\Api\Orders','reid','id',[],'LEFT')->select('order_id','status','trade_type','pay_time','return_time','total_amount');
    }

    public function recode()
    {
        return $this->belongsTo('App\Models\Api\Recode','rid');
    }

    public function getRectifications($map = [])
    {
        $uid = $map['uid'];
        $page = $map['page'];

        $goods = (new Goods())->getGoods(['id' => 1]);// 生时校正商品

        if(intval($this->cache_on) >= 1 && Cache::has('goods') && Cache::has('rectification_'.$uid))
        {
            $goods = Cache::get('goods');

            $data = Cache::get('rectification_'.$uid);
        }

        if(empty($data))
        {
            try
            {
                // 要查询的字段
                $field = ['re.id','re.status','re.start_time','re.end_time','re.create_time','or.order_id','or.trade_type','or.total_amount'];
                $where = [
                    're.uid'=>$uid,
                    ['re.status','!=',config('code.status_delete')]
                ];
                $order = 're.id DESC';

                $data = $this->from('rectification as re')
                    ->join('orders as or','or.reid','=','re.id','RIGHT')
                    ->where($where)
                    ->orderBy('re.id','DESC')
                    ->paginate(10,$field,$page);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), $e->getMessage());
            }
        }




        foreach ($data as $k => $d)
        {
            $data[$k]['or_prize'] = $goods['or_prize'];

            $data[$k]['now_prize'] = $goods['now_prize'];
        }

        return $data;
    }
}